/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package warehouse;


import archive.ReportActionForm;
import ejb.archive.Allegato;
import ejb.archive.AllegatoFacadeRemote;
import ejb.archive.Report;
import ejb.archive.ReportFacadeRemote;
import ejb.warehouse.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import system.Utilities;

import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import system.LoginActionForm;

/**
 *
 * @author ciummo
 */
public class OrderAction extends DispatchAction {

    /*
     * forward name="success" path=""
     */
    private final static String SUCCESS = "success";
    private final static String TONEWORDER = "toNewOrder";
    private final static String TOORDERSLIST = "toOrdersList";
    private final static String TOORDERDETAILS = "toOrderDetails";
    private final static String TOMODIFYORDER = "toModifyOrder";
    private final static String SUCCESSSUBMITORDER = "successSubmitOrder";
    private final static String SUCCESSDELETEORDER = "successDeleteOrder";
    private final static String SUCCESSLISTWORK = "successListWork";
    
    
    public static final String DATE_FORMAT_NOW = "yyyy-MM-dd";
    private Calendar cal = Calendar.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
    
    
    
    private Utilities utility = new Utilities();
    
            public ActionForward listWork(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
                    
                OrdineFacadeRemote ordineFacade = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
                OrdineProdottoFacadeRemote ordineProdottoFacade = (OrdineProdottoFacadeRemote) utility.callRemoteBean("OrdineProdottoFacade/remote");
                
                OrderActionForm orderForm = (OrderActionForm) form;
                
                List <Ordine> listaOrdini ;
                listaOrdini = ordineFacade.findAll();
            
                List <OrderActionForm> listaOrderForm = new ArrayList();;

                OrderActionForm orderActionForm;
                
                for (int i=0; i<listaOrdini.size(); i++){

                    orderActionForm = new OrderActionForm();
                    
                    orderActionForm.setDataEvasione(listaOrdini.get(i).getDataEvasione());
                    orderActionForm.setIdOrdine(listaOrdini.get(i).getIdOrdine());
                    orderActionForm.setStato(listaOrdini.get(i).getStato());
                    
                    
                    OrdineProdottoBeanToOrderProductForm toProductForm = new OrdineProdottoBeanToOrderProductForm();
                    
                    //List <OrdineProdotto> ordineProdotto = ordineProdottoFacade.findOrdineProdottiByIdOrdine(listaOrdini.get(i).getIdOrdine());
                    List <OrderProductActionForm> listOrderProductForm = toProductForm.convert(ordineProdottoFacade.findOrdineProdottiByIdOrdine(listaOrdini.get(i).getIdOrdine()));
                    
                    orderActionForm.setListOrderProductForm(listOrderProductForm);
                    
                    //orderActionForm.setListOrdineProdotto(ordineProdottoFacade.findOrdineProdottiByIdOrdine(listaOrdini.get(i).getIdOrdine()));

                    listaOrderForm.add(orderActionForm);
                }
                
               
                
                //System.out.println(listaOrderForm.get(0).getListOrdineProdotto().get(0).getCodArticolo());
                
                orderForm.setListOrderForm(listaOrderForm);
                
                
                
                //System.out.println(listaOrderForm.size());
                
        
        return mapping.findForward(SUCCESSLISTWORK);
    } 

    public ActionForward setReady(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        int idOrder;

        try{
            idOrder = Integer.parseInt(request.getParameter("idOrder"));
        }catch(NumberFormatException nfe){

            idOrder = Integer.parseInt(request.getSession().getAttribute("idOrder").toString());
        }
        
        OrdineFacadeRemote ordineFacade = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
        
        Ordine ordine = ordineFacade.find(idOrder);
        
        if(ordine.getStato().equalsIgnoreCase("In Elaborazione")){
            
            ordine.setStato("Pronto");
            ordineFacade.edit(ordine);
            
        }
        
        request.getSession().setAttribute("id", ordine.getIdOrdine());
        
        ReportFacadeRemote reportFacade = (ReportFacadeRemote) utility.callRemoteBean("ReportFacade/remote");
        Report report = new Report();
        
        report.setCodRiferimento(Integer.toString(idOrder));
        report.setData(sdf.format(cal.getTime()));
        
        LoginActionForm loginForm = (LoginActionForm) request.getSession().getAttribute("LoginActionForm"); 
        
        report.setIdUtente(loginForm.getUsername());
        //report.setMessaggio(SUCCESS);
        report.setTipo("Ordine Pronto");
        
        reportFacade.create(report);
        
        
        
        return mapping.findForward(SUCCESSSUBMITORDER);
    }    
    
    
    
    public ActionForward newOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
            
        OrderActionForm orderForm = (OrderActionForm) form;
        orderForm.reset(mapping, request);
        request.getSession().setAttribute("OrderActionForm", null);
        
               
        return mapping.findForward(TONEWORDER);
    }

    public ActionForward submitOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        OrderActionForm orderForm = (OrderActionForm) form;
               
        
        ActionErrors errors = form.validate(mapping, request);

        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return  mapping.findForward(TONEWORDER);
        }
        
        
        
        OrdineFacadeRemote ordini = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
        
        Ordine newOrder = new Ordine();
        
        newOrder.setIdOrdine(orderForm.getIdOrdine());
        newOrder.setDataEvasione(orderForm.getDataEvasione());
        newOrder.setResoFranco(orderForm.getResoFranco());
        newOrder.setTipoPagamento(orderForm.getTipoPagamento());
        newOrder.setStato("In Elaborazione");
        newOrder.setNote(orderForm.getNote());
        
        ordini.create(newOrder);
        
        request.getSession().setAttribute("id", orderForm.getIdOrdine());

        ReportFacadeRemote reportFacade = (ReportFacadeRemote) utility.callRemoteBean("ReportFacade/remote");
        Report report = new Report();
        
        report.setCodRiferimento(Integer.toString(orderForm.getIdOrdine()));
        report.setData(sdf.format(cal.getTime()));
        
        LoginActionForm loginForm = (LoginActionForm) request.getSession().getAttribute("LoginActionForm"); 
        
        report.setIdUtente(loginForm.getUsername());
        report.setTipo("Ordine Creato");
        reportFacade.create(report);
        
        
        return mapping.findForward(SUCCESSSUBMITORDER);
    }
    
    public ActionForward listOrders(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
            
        //TODO Prima o poi questo e' da togliere 
        
        String view = request.getParameter("view");
        try{
               
               view.compareTo("non deve essere null");
        }catch(NullPointerException e){
            
            view="all";
        }
        
        System.out.println(view);
        
        OrdineFacadeRemote ordine = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
        OrderActionForm order = (OrderActionForm) form;

        if (view.equalsIgnoreCase("all")){
        
            order.setList(ordine.findAll());
        }
        
        else {
            
            order.setList(ordine.findOrdiniByStato(view));
        }
        
        request.getSession().setAttribute("view", view);
        
        return mapping.findForward(TOORDERSLIST);
    }    

    public ActionForward orderDetails(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        int id;
        
        
        try{
               id = Integer.parseInt(request.getParameter("id"));
        }catch(NumberFormatException nfe){
            
            id = Integer.parseInt(request.getSession().getAttribute("id").toString());
        }
                
        RetrieveOrderFormById retrieveOrder = new RetrieveOrderFormById();
        
        OrderActionForm orderForm = retrieveOrder.retrieve(id);
        
        
        request.getSession().setAttribute("OrderActionForm", orderForm);
               
        //CARICO LA LISTA DEGLI ORDINE-ARTICOLI
        
        OrdineProdottoFacadeRemote ordineProdottoFacade = (OrdineProdottoFacadeRemote) utility.callRemoteBean("OrdineProdottoFacade/remote");
            
        OrderProductActionForm orderProductForm = new OrderProductActionForm();
        
        List <OrdineProdotto> listaOrdineProdotto = ordineProdottoFacade.findOrdineProdottiByIdOrdine(id);
        
        OrdineProdottoBeanToOrderProductForm ordineProdottoToOrderProduct = new OrdineProdottoBeanToOrderProductForm();
        
        orderProductForm.setListOrderProductForm(ordineProdottoToOrderProduct.convert(listaOrdineProdotto));
        
        request.getSession().setAttribute("OrderProductActionForm", orderProductForm);
        
        //////////////////////////////////////
        
        ReportFacadeRemote reportFacade = (ReportFacadeRemote) utility.callRemoteBean("ReportFacade/remote");
        
        ReportActionForm reportForm = new ReportActionForm();
        
        reportForm.setList(reportFacade.findReportByCode(Integer.toString(id)));
        
        request.getSession().setAttribute("ReportActionForm", reportForm);
        
        ///////////////////////////////////////
        
        AllegatoFacadeRemote allegatoFacade = (AllegatoFacadeRemote) utility.callRemoteBean("AllegatoFacade/remote");
        
        //ORDINE
        List <Allegato> allegati = allegatoFacade.findAllegatoByIdRiferimentoAndTipo(Integer.toString(id), "Ordine");
        
        if (!allegati.isEmpty()){
            
            request.getSession().setAttribute("AllegatoOrdine", allegati.get(0));
        }
        else {
            
            request.getSession().setAttribute("AllegatoOrdine", null);
        }
        
        //BOLLA
        
        allegati = allegatoFacade.findAllegatoByIdRiferimentoAndTipo(Integer.toString(id), "Bolla");
        
        if (!allegati.isEmpty()){
            
            request.getSession().setAttribute("AllegatoBolla", allegati.get(0));
        }
        else {
            
            request.getSession().setAttribute("AllegatoBolla", null);
        }
        
        //FATTURA
               
        allegati = allegatoFacade.findAllegatoByIdRiferimentoAndTipo(Integer.toString(id), "Fattura");
        
        if (!allegati.isEmpty()){
            
            request.getSession().setAttribute("AllegatoFattura", allegati.get(0));
        }
        else {
            
            request.getSession().setAttribute("AllegatoFattura", null);
        }
        
        //////////////////////////////////////
        
        
        request.getSession().setAttribute("idOrder", orderForm.getIdOrdine());
        
        return mapping.findForward(TOORDERDETAILS);
    }     
    
    
        public ActionForward modifyOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        int idOrder = Integer.parseInt(request.getParameter("idOrder"));
        
        RetrieveOrderFormById retrieveOrder = new RetrieveOrderFormById();
        
        OrderActionForm orderForm = retrieveOrder.retrieve(idOrder);
        
        
        
        request.getSession().setAttribute("OrderActionForm", orderForm);
        
        return mapping.findForward(TOMODIFYORDER);
    }
        
        public ActionForward submitModifyOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
                    
            OrderActionForm orderForm = (OrderActionForm) form;
        
            ModifyOrdine mop = new ModifyOrdine();
            
            mop.Modify(orderForm);
            
            request.getSession().setAttribute("id", orderForm.getIdOrdine());

        
        return mapping.findForward(SUCCESSSUBMITORDER);
    }      
    
        public ActionForward deleteOrder(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
                    
            int idOrder = Integer.parseInt(request.getParameter("idOrder"));
            
            OrdineFacadeRemote ordineFacade = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
            
            ordineFacade.remove(ordineFacade.find(idOrder));
            
        
        return mapping.findForward(SUCCESSDELETEORDER);
    }      
        
            
    
    
}

class RetrieveOrderFormById {
    
    
    Utilities utility = new Utilities();
    
    public OrderActionForm retrieve (int id) throws NamingException{
        
        
        OrderActionForm orderForm = new OrderActionForm();
        
        OrdineFacadeRemote ordineFacade = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");

        
        //QUI DEVO ANCORA METTERE UN TRY
        
        Ordine ordine = ordineFacade.findOrdineById(id);
        
        //IF NULL...
        
        orderForm.setIdOrdine(ordine.getIdOrdine());
        orderForm.setDataEvasione(ordine.getDataEvasione());
        orderForm.setTipoPagamento(ordine.getTipoPagamento());
        orderForm.setResoFranco(ordine.getResoFranco());
        orderForm.setStato(ordine.getStato());
        orderForm.setNote(ordine.getNote());
        
        
        
        return orderForm;
    }
}

class ModifyOrdine {
    
    
        Utilities utility = new Utilities();

    
    public boolean Modify (OrderActionForm orderForm) throws NamingException{
        
        
            OrdineFacadeRemote ordineFacade = (OrdineFacadeRemote) utility.callRemoteBean("OrdineFacade/remote");
        
            Ordine ordine = ordineFacade.find(orderForm.getIdOrdine());
            
            ordine.setDataEvasione(orderForm.getDataEvasione());
            ordine.setResoFranco(orderForm.getResoFranco());
            ordine.setTipoPagamento(orderForm.getTipoPagamento());
            ordine.setStato(orderForm.getStato());
            ordine.setNote(orderForm.getNote());
            
           
            
            ordineFacade.edit(ordine);
            
            return true;
            
        
    }
    
    
}   


class OrdineProdottoBeanToOrderProductForm {
    
    Utilities utility = new Utilities();
    
    List <OrderProductActionForm> convert (List<OrdineProdotto> listaOrdineProdotto) throws NamingException{
        
        
        List <OrderProductActionForm> listOrderProductForm = new ArrayList();
        
        
        for (int i=0; i<listaOrdineProdotto.size();i++){
                    
            OrderProductActionForm orderProductForm = new OrderProductActionForm();

            orderProductForm.setIdOrdineProdotto(listaOrdineProdotto.get(i).getIdOrdineProdotto());
            orderProductForm.setCodArticolo(listaOrdineProdotto.get(i).getCodArticolo());
            
            ProdottoFacadeRemote prodottoFacade = (ProdottoFacadeRemote) utility.callRemoteBean("ProdottoFacade/remote");
            
            
            orderProductForm.setQuantita(listaOrdineProdotto.get(i).getQuantita());
            
            int numeroProdotti = prodottoFacade.findProdottiByIdOrdineProdotto(listaOrdineProdotto.get(i).getIdOrdineProdotto()).size();
            
            orderProductForm.setMancanti(listaOrdineProdotto.get(i).getQuantita() - numeroProdotti);
            orderProductForm.setStato(listaOrdineProdotto.get(i).getStato());

            ArticoloFacadeRemote articoloFacade = (ArticoloFacadeRemote) utility.callRemoteBean("ArticoloFacade/remote");
            orderProductForm.setNomeArticolo(articoloFacade.find(orderProductForm.getCodArticolo()).getNome());

            listOrderProductForm.add(orderProductForm);
        
        }
        
        return listOrderProductForm;
        
    }
    
    
    
    
    
    
    
}